package com.xiaoxi.open.design.creation.prototypepattern.manager;

import com.xiaoxi.open.design.creation.prototypepattern.product.IProduct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author xiaoxi
 * @ProjectName creation_pattern
 * @PackageName com.xiaoxi.open.design.creation.prototypepattern.manager
 * @ClassName ProductManager
 * @Description TODO
 * @Date 2024/5/17 11:10
 * @Version 1.0
 */
@Service
@Slf4j
public class ProductManager implements ApplicationContextAware {

    private Map<String, IProduct> productMap = new HashMap<>();

    public void register(String productName, IProduct product) {
        productMap.put(productName, product);
    }

    public IProduct cloneProduct(String productName) {
        return productMap.get(productName).createClone();
    }

    public IProduct getParentProduct(String productName) {
        return productMap.get(productName);
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //根据接口类型返回相应的所有bean
        Map<String, IProduct> beansOfType = applicationContext.getBeansOfType(IProduct.class);
        for (Map.Entry<String, IProduct> entry : beansOfType.entrySet()) {
            IProduct value = entry.getValue();
            value.init();
            register(entry.getKey(), value);
        }
    }
}
